package com.juanable.niubility.designPatterns;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: lyg
 * @Data: 2022/8/8
 *
 * 提前加载关于StrategyHandler的实现类
 * 要通过这个调用doHandler()执行.
 */
@Component
public class StatementClient<T> implements InitializingBean {

    // InitializingBean: 实现这个接口可以完成初始化的工作: 重写afterPropertiesSet.

    @Resource
    private ApplicationContextHelper applicationContextHelper;

    /**
     * 存放处理handler实现类的集合
     */
    private Map<String, StrategyHandler> TypeAndStatementHandle = new ConcurrentHashMap<>();

    /**
     * initializingBean的初始化接口
     * 从ApplicationContextHelper里面获取到的bean 都放到map里面去，map的key为实现的handler的业务tag,值为该对象
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        /**
         * 从ApplicationContextHelper里面获取到的bean 都放到map里面去，map的key为枚举中的值,值为该对象(自己的)
         */
        Map<String, StrategyHandler> statementHandles = applicationContextHelper.getBeansOfType(StrategyHandler.class);
        for (Map.Entry<String, StrategyHandler> StatementHandle : statementHandles.entrySet()) {
            TypeAndStatementHandle
                    .put(StatementHandle.getValue().getType().desc, StatementHandle.getValue());
        }

    }

    /**
     * 对外提供方法调用
     *
     * @param tag
     * @param t
     */
    public void doHandler(String tag,T t) {
        TypeAndStatementHandle.get(tag).process(t);
    }
}
